package com.gupao.alg.alg1;

import java.util.ArrayList;

public class ReverseListPrint {
    /**
     * 倒序打印链表
     */

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
        ListNode node = initLinkedList(a);
        int[] result;
        result = reversePrint(node);
        System.out.println(result);
    }

    public static int[] reversePrint(ListNode head) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        recur(head, result);
        int[] res = new int[result.size()];
        for (int i = 0; i < res.length; i++)
            res[i] = result.get(i);
        return res;
    }

    public static void recur(ListNode head, ArrayList<Integer> result) {
        if (head == null) return;
        recur(head.next, result);
        result.add(head.val);
    }


    private static ListNode initLinkedList(int[] array) {
        ListNode head = null, cur = null;
        for (int i = 0; i < array.length; i++) {
            ListNode newNode = new ListNode(array[i]);
            newNode.next = null;
            if (i == 0) {
                head = newNode;
                cur = head;
            } else {
                cur.next = newNode;
                cur = newNode;
            }
        }
        return head;
    }

    static class ListNode {
        public int val;
        public ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
